package com.pr.makfilm.user.pages.school.list.cmp;

import com.pr.makfilm.core.cmp.notify.Notification;
import com.pr.makfilm.core.cmp.web.BootstrapTextArea;
import com.pr.makfilm.core.cmp.web.BootstrapTextFieldPanel;
import com.pr.makfilm.core.cmp.window.AbstractWindow;
import com.pr.makfilm.domain.District;
import com.pr.makfilm.service.IDistrictService;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.StringValidator;

/**
 * Created with IntelliJ IDEA.
 * User: Balbina
 * Date: 08.12.13
 * Time: 15:58
 * To change this template use File | Settings | File Templates.
 */
public abstract class DistrictWindow extends AbstractWindow<District>
{
   @SpringBean
   private IDistrictService districtService;

   private boolean createMode = true;

   public DistrictWindow(String id)
   {
      super(id, Model.of(new District()), new Model<String>());
   }

   @Override
   protected void onInitialize()
   {
      super.onInitialize();
      BootstrapTextFieldPanel name = new BootstrapTextFieldPanel("name", new PropertyModel(this, "district." + District.FIELD_NAME));
      name.setValidation(true);
      name.getField().add(StringValidator.maximumLength(District.MAX_LENGTH_NAME));
      form.add(name);

      BootstrapTextArea description = new BootstrapTextArea("description", new PropertyModel(this, "district." + District.FIELD_DESCRIPTION));
      description.setValidation(false);
      form.add(description);
   }

   public void resetState(boolean createMode)
   {
      this.createMode = createMode;
      if (createMode)
      {
         setDistrict(new District());
      }
      setHeader(createMode ? getString("create.title") : getString("edit.title"));
   }

   @Override
   public void onSubmit(AjaxRequestTarget target, Form<?> form)
   {
      District district = getDistrict();
      if (createMode())
      {
         districtService.save(district);
         Notification.success(getString("district.successfully.saved"));
      }
      else
      {
         District old = districtService.getBySid(district.getSid());
         old.setName(district.getName());
         old.setDescription(district.getDescription());
         districtService.update(old);
         Notification.success(getString("district.successfully.updated"));
      }
   }

   public boolean createMode()
   {
      return createMode;
   }

   public District getDistrict()
   {
      return (District) getDefaultModelObject();
   }

   public void setDistrict(District district)
   {
      setDefaultModelObject(district);
   }
}
